/* $RCSFile: CrmServerManager.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/PageModules/CrmServerManager/CrmServerManager.ascx.cs $
 * $log$
 * Revision 20 2010/08/09 10:51:20  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 19 2010/08/09 09:43:51  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:25  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Linq;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Drawing;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Globalization;

using AddonNice.UI;
using AddonNice.UI.WebControls;
using AddonNice.UI.DataTypes;
using AddonNice.Configuration;
using AddonNice.Settings;
using AddonNice.Helpers;
using AddonNice.Diagnostics;
using AddonNice.Configuration.Settings;
using AddonNice.Core;
using AddonNice.CRMWrapper;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.PageModules.CrmServerManager
{

    /// <summary>
    /// Initializer for CrmServerManager 
    /// </summary>
    public class CrmServerManagerSI : CrmServerManagerBaseSI
    {
        public CrmServerManagerSI(ModuleSettingsDictionary bSettings,ISettingsOwner pm) : base()
        {
            if ( CrmServerManTrace.Sw.TraceVerbose )
                Trace2.WriteLine("[V]CrmServerManagerSI Ctor BEG.",CrmServerManTrace.Sw.Info);
            InitSettings(bSettings,pm);
            if ( CrmServerManTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmServerManagerSI Ctor END.",CrmServerManTrace.Sw.Info);
        }

        public override void InitSettings(ModuleSettingsDictionary bSettings,ISettingsOwner pm)
        {             
            if ( CrmServerManTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmServerManagerSI InitSettings BEG.",CrmServerManTrace.Sw.Info);
            base.InitSettings(bSettings,pm);


            if ( CrmServerManTrace.Sw.TraceVerbose )
                Trace2.WriteLine("[V]CrmServerManagerSI InitSettings END.",CrmServerManTrace.Sw.Info);
        }
    }

    /// <summary>
    /// Input Rating about an Item
    /// </summary>
    public partial class CrmServerManager : PortalCRMModuleControl 
    {
		CrmDB CrmManDB      =   new CrmDB();

		#region General Implementation

        public override bool NeedAttachedEntity
        {
            get
            {
                return false;
            }
        }

		public override Guid GuidID 
		{
			get
			{
				return new Guid("{7353B8ED-CDD2-46a5-8BAD-91E29EEAB42A}");
			}
		}

        public override bool AdminModule
        {
            get
            {
                return true;
            }
        }


		#endregion

        /// <summary>
        /// Public constructor. Sets base settings for module.
        /// </summary>
        public CrmServerManager() 
        {
            if ( CrmServerManTrace.Sw.TraceVerbose )
                Trace2.WriteLine("[V]CrmServerManager Ctor END.",CrmServerManTrace.Sw.Info);
        }

        public override void InitPortalModuleControl(ModuleSettingsDictionary bSettings)
        {
            PortalModuleInitializer =   new CrmServerManagerSI(bSettings,this);
        }


        /// <summary>
        /// The Page_Load event handler on this User Control is used to
        /// obtain a DataSet of announcement information from the CrmServerManager
        /// table, and then databind the results to a templated DataList
        /// server control.  It uses the AddonNice.CrmServerManagerDB()
        /// data component to encapsulate all data functionality. 
        /// </summary>
        protected void Page_Load(object sender, System.EventArgs e) 
        {
			if (CrmServerManTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmServerManager Page_Load Time: {0}, IsPostBack: {1}",DateTime.UtcNow,IsPostBack),CrmServerManTrace.Sw.Info);
            if ( !IsPostBack )
            {
            }
			if (CrmServerManTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmServerManager Page_Load END.",CrmServerManTrace.Sw.Info);
        }

        void RadGrid1_NeedDataSource(object source,GridNeedDataSourceEventArgs e)
        {
			if (CrmServerManTrace.Sw.TraceVerbose)
                Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]CrmServerManager RadGrid1_NeedDataSource BEG Reason: {0}.",e.RebindReason),CrmServerManTrace.Sw.Info);
            try
            {
                DataTable Tb        =   CrmManDB.GetAllCrmServerTb();
                RadGrid1.DataSource =   Tb;
            }
            catch ( Exception ex )
            {
			    if (CrmServerManTrace.Sw.TraceError)
                    Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[E]CrmServerManager RadGrid1_NeedDataSource ex: {0}.",ex),CrmServerManTrace.Sw.Info);
                throw;
            }
			if (CrmServerManTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmServerManager RadGrid1_NeedDataSource END .",CrmServerManTrace.Sw.Info);
        }

        void RadGrid2_NeedDataSource(object source,GridNeedDataSourceEventArgs e)
        {
			if (CrmServerManTrace.Sw.TraceVerbose)
                Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]CrmServerManager RadGrid2_NeedDataSource BEG Reason: {0}.",e.RebindReason),CrmServerManTrace.Sw.Info);
            try
            {
                int CrmServerID     =   (RadGrid1.SelectedValue == null ) ? -1:(int)RadGrid1.SelectedValue;
                RadGrid2.DataSource =   CrmManDB.GetPortalsByCrmServerTb(CrmServerID);
            }
            catch ( Exception ex )
            {
			    if (CrmServerManTrace.Sw.TraceError)
                    Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[E]CrmServerManager RadGrid2_NeedDataSource ex: {0}.",ex),CrmServerManTrace.Sw.Info);
                throw;
            }
			if (CrmServerManTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmServerManager RadGrid2_NeedDataSource END .",CrmServerManTrace.Sw.Info);
        }

        void RadGrid3_NeedDataSource(object source,GridNeedDataSourceEventArgs e)
        {
			if (CrmServerManTrace.Sw.TraceVerbose)
                Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]CrmServerManager RadGrid3_NeedDataSource BEG Reason: {0}.",e.RebindReason),CrmServerManTrace.Sw.Info);
            try
            {
                int CrmServerID     =   (RadGrid1.SelectedValue == null ) ? -1:(int)RadGrid1.SelectedValue;
                RadGrid3.DataSource =   CrmManDB.GetEntitiesByCrmServerTb(CrmServerID);
            }
            catch ( Exception ex )
            {
			    if (CrmServerManTrace.Sw.TraceError)
                    Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[E]CrmServerManager RadGrid3_NeedDataSource ex: {0}.",ex),CrmServerManTrace.Sw.Info);
                throw;
            }
			if (CrmServerManTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmServerManager RadGrid3_NeedDataSource END .",CrmServerManTrace.Sw.Info);
        }

        #region RadGrid for Crm Servers

        void RadGrid1_SelectedIndexChanged(object sender,EventArgs e)
        {
            bool hasSel                                             =   RadGrid1.SelectedValue != null ;
			if (CrmServerManTrace.Sw.TraceVerbose)
                Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]CrmServerManager RadGrid1_SelectedIndexChanged BEG hasSel: {0}.",hasSel),CrmServerManTrace.Sw.Info);
            if ( !hasSel  )
            {
                RadGrid2.MasterTableView.CommandItemDisplay         =   GridCommandItemDisplay.None;
                RadGrid3.MasterTableView.CommandItemDisplay         =   GridCommandItemDisplay.None;
            }
            else
            {
                int CrmServerID                                     =   (int)RadGrid1.SelectedValue;
                RefreshCommands(CrmServerID);
            }
            RadGrid2.Rebind();
            RadGrid3.Rebind();
			if (CrmServerManTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmServerManager RadGrid1_SelectedIndexChanged END.",CrmServerManTrace.Sw.Info);
        }

        ArrayList MakeAuthentication()
        {
            ArrayList ar    =   new ArrayList();
            Type t          =   typeof(ADNAuthenticationType);
            ListItem it     =   new ListItem(Enum.GetName(t,ADNAuthenticationType.AD),((int)ADNAuthenticationType.AD).ToString());
            ar.Add(it);
            it              =   new ListItem(Enum.GetName(t,ADNAuthenticationType.Online),((int)ADNAuthenticationType.Online).ToString());
            ar.Add(it);
            it              =   new ListItem(Enum.GetName(t,ADNAuthenticationType.SPLA),((int)ADNAuthenticationType.SPLA).ToString());
            ar.Add(it);
            return ar;
        }

        void RefreshCommands(int CrmServerID)
        {
            int CountOther                                      =   0;
            int Count                                           =   CrmManDB.ExistPortalsByCrmServer(CrmServerID,ref CountOther);
            if ( ( CountOther > 0 ) || ( Count > 0 ) )// No portals, not necessary to offered adding 
            {
                RadGrid2.MasterTableView.CommandItemDisplay     =   GridCommandItemDisplay.Top;
            }
            else
                RadGrid2.MasterTableView.CommandItemDisplay     =   GridCommandItemDisplay.None;
            CountOther                                          =   0;
            Count                                               =   CrmManDB.ExistCrmEntityByCrmServer(CrmServerID,ref CountOther);
            if ( ( CountOther > 0 ) || (Count > 0 ) ) // No entities, not necessary to offered adding 
                    RadGrid3.MasterTableView.CommandItemDisplay =   GridCommandItemDisplay.Top;
            else    RadGrid3.MasterTableView.CommandItemDisplay =   GridCommandItemDisplay.None;
        }

        void RadGrid1_DataBound(object sender,EventArgs e)
        {
			if (CrmServerManTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmServerManager RadGrid1_DataBound BEG RadGrid1.Items.Count: {0}",RadGrid1.Items.Count),CrmServerManTrace.Sw.Info);
            if ( RadGrid1.Items.Count > 0 )
            {
                if( RadGrid1.SelectedValue == null )
                    RadGrid1.Items[0].Selected                      =   true;
                int CrmServerID                                     =   (int)RadGrid1.SelectedValue;
                RefreshCommands(CrmServerID);
            }
            else
            {
                RadGrid2.MasterTableView.CommandItemDisplay         =   GridCommandItemDisplay.None;
                RadGrid3.MasterTableView.CommandItemDisplay         =   GridCommandItemDisplay.None;
            }
			if (CrmServerManTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmServerManager RadGrid1_DataBound END.",CrmServerManTrace.Sw.Info);
        }

        void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if ( !( e.Item is GridEditableItem ) )
                return;
            GridEditableItem Item                           =   e.Item as GridEditableItem;
			if (CrmServerManTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmServerManager RadGrid1_ItemDataBound BEG IsInEditMode: {0}",Item.IsInEditMode),CrmServerManTrace.Sw.Info);
            
            if (Item.IsInEditMode)
            {
                DataRowView rw                              =   null;
                if ( !Item.OwnerTableView.IsItemInserted )
                    rw                                      =   (DataRowView)e.Item.DataItem;
                GridEditManager editMan                     =   Item.EditManager;

                GridDropDownListColumnEditor editor =   (GridDropDownListColumnEditor)editMan.GetColumnEditor( "AuthenticationType" );
                //in case you have RadComboBox editor for the GridDropDownColumn (this is the default editor),         
                //you will need to use ComboBoxControl below instead of DropDownListControl
                //Then you can modify the list control as per your custom conventions
                editor.DataSource                           =   MakeAuthentication();
                editor.DataBind();
                if (rw != null)
                {
                    RadComboBoxItem it                      =   editor.ComboBoxControl.Items.FindItemByValue(rw["AuthenticationType"].ToString());
                    if (it != null)
                        it.Selected                         =   true;
                }
            }
            else
            {
                // adapt the Main portal
                DataRowView rw                              =   (DataRowView)e.Item.DataItem;
                object ob                                   =   rw["MainPortalID"];
                if ( ( ob != null ) && (ob is int) )
                {
                    int MainPortalID                        =   (int)ob;
                    DBPortal prtObj                         =   new PortalsDB().GetPortalObj(MainPortalID);
                    Item["MainPortalID"].Text               =   prtObj.PortalAlias;
                }
                else Item["MainPortalID"].Text              =   string.Empty;

                // adapt the authentication type
                ADNAuthenticationType ival                  =   (ADNAuthenticationType)(int)rw["AuthenticationType"];
                if (CrmServerManTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmServerManager RadGrid1_ItemDataBound AuthenticationType: {0}",ival),CrmServerManTrace.Sw.Info);
                Type t                                      =   typeof(ADNAuthenticationType);
                Item["AuthenticationType"].Text             =   Enum.GetName(t,ival);
            }
			if (CrmServerManTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmServerManager RadGrid1_ItemDataBound END.",CrmServerManTrace.Sw.Info);
        }

        void RadGrid1_UpdateCommand(object source, GridCommandEventArgs e)
        {
			if (CrmServerManTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmServerManager RadGrid1_UpdateCommand BEG OwnerTableView.Name: {0}",e.Item.OwnerTableView.Name),CrmServerManTrace.Sw.Info);
            GridEditableItem editedItem     =   e.Item as GridEditableItem;
            Hashtable newValues             =   new Hashtable();
            e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);
            try
            {
                int CrmServerID             =   (int)(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex][ "CrmServerId"]);
                string FriendlyName         =   (string)newValues["Friendlyname"];
                int CrmVersion              =   int.Parse(newValues["CrmVersion"].ToString());
                bool UsePreAuthenticate     =   bool.Parse(newValues["UsePreAuthenticate"].ToString());
	            string Organization         =   (string)newValues["Organization"];
	            string DiscoServer          =   (string)newValues["DiscoServer"];
	            string Server3              =   (string)newValues["Server3"];
	            
                string ServiceAccount       =   (string)newValues["ServiceAccount"];
	            string ServicePassword      =   (string)newValues["ServicePassword"];
	            string ServiceDomain        =   (string)newValues["ServiceDomain"];

                string PrivAccount          =   (string)newValues["PrivAccount"];
	            string PrivPassword         =   (string)newValues["PrivPassword"];
	            string PrivDomain           =   (string)newValues["PrivDomain"];

                string DefaultAccount       =   (string)newValues["DefaultAccount"];
	            string DefaultPassword      =   string.Empty;
                if ( newValues.ContainsKey("DefaultAccountPassword") )
	                DefaultPassword         =   (string)newValues["DefaultAccountPassword"];
	            string DefaultDomain        =   string.Empty;
                if ( newValues.ContainsKey("DefaultAccountDomain") )
	                DefaultDomain           =   (string)newValues["DefaultAccountDomain"];

	            string AdminRoleName        =   string.Empty;
                if ( newValues.ContainsKey("AdminRoleName") )
                    AdminRoleName        =   (string)newValues["AdminRoleName"];

                int AuthenticationType      =   int.Parse(newValues["AuthenticationType"].ToString());
	            int DiscoServerPort         =   int.Parse(newValues["DiscoServerPort"].ToString());
                CrmManDB.UpdateCrmServer(CrmServerID,FriendlyName,CrmVersion,UsePreAuthenticate,Organization,AuthenticationType,DiscoServer,DiscoServerPort,Server3,
	                                ServiceAccount,ServicePassword,ServiceDomain,PrivAccount,PrivPassword,PrivDomain,DefaultAccount,DefaultPassword,DefaultDomain,AdminRoleName);
		        if (CrmServerManTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmServerManager RadGrid1_UpdateCommand END CrmServerID: {0}, FriendlyName: {1}",CrmServerID,FriendlyName),CrmServerManTrace.Sw.Info);
            }
            catch (Exception ex)
            {
			    if (CrmServerManTrace.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmServerManager RadGrid1_UpdateCommand ex: {0}",ex),CrmServerManTrace.Sw.Info);
                throw;
            }
            return;
        }

        private void RadGrid1_InsertCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
        {
			if (CrmServerManTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmServerManager RadGrid1_InsertCommand BEG OwnerTableView.Name: {0}",e.Item.OwnerTableView.Name),CrmServerManTrace.Sw.Info);
            GridEditableItem Item           =   e.Item as GridEditableItem;

            Hashtable newValues             =   new Hashtable();
            e.Item.OwnerTableView.ExtractValuesFromItem(newValues, Item);

            try
            {
                string FriendlyName         =   (string)newValues["Friendlyname"];
                int CrmVersion              =   int.Parse(newValues["CrmVersion"].ToString());
                bool UsePreAuthenticate     =   bool.Parse(newValues["UsePreAuthenticate"].ToString());
	            string Organization         =   (string)newValues["Organization"];
	            string DiscoServer          =   string.Empty;
                if ( newValues.ContainsKey("DiscoServer") )
	                DiscoServer             =   (string)newValues["DiscoServer"];
                string Server3              =   string.Empty;
                if ( newValues.ContainsKey("Server3") )
	                Server3                 =   (string)newValues["Server3"];
	            
                string ServiceAccount       =   (string)newValues["ServiceAccount"];
	            string ServicePassword      =   (string)newValues["ServicePassword"];
	            string ServiceDomain        =   (string)newValues["ServiceDomain"];

                string PrivAccount          =   (string)newValues["PrivAccount"];
	            string PrivPassword         =   (string)newValues["PrivPassword"];
	            string PrivDomain           =   (string)newValues["PrivDomain"];

                string DefaultAccount       =   (string)newValues["DefaultAccount"];
	            string DefaultPassword      =   string.Empty;
                if ( newValues.ContainsKey("DefaultAccountPassword") )
	                DefaultPassword         =   (string)newValues["DefaultAccountPassword"];
	            string DefaultDomain        =   string.Empty;
                if ( newValues.ContainsKey("DefaultAccountDomain") )
	                DefaultDomain           =   (string)newValues["DefaultAccountDomain"];

	            string AdminRoleName        =   string.Empty;
                if ( newValues.ContainsKey("AdminRoleName") )
                    AdminRoleName        =   (string)newValues["AdminRoleName"];

                int AuthenticationType      =   int.Parse(newValues["AuthenticationType"].ToString());
	            int DiscoServerPort         =   int.Parse(newValues["DiscoServerPort"].ToString());

                int CrmServerID             =   CrmManDB.AddCrmServer(FriendlyName,CrmVersion,UsePreAuthenticate,Organization,AuthenticationType,DiscoServer,DiscoServerPort,Server3,
	                                ServiceAccount,ServicePassword,ServiceDomain,PrivAccount,PrivPassword,PrivDomain,DefaultAccount,DefaultPassword,DefaultDomain,AdminRoleName);
		        if (CrmServerManTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmServerManager RadGrid1_InsertCommand END CrmServerID: {0}, FriendlyName: {1}",CrmServerID,FriendlyName),CrmServerManTrace.Sw.Info);
            }
            catch (Exception ex)
            {
				if (CrmServerManTrace.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmServerManager RadGrid1_InsertCommand ex: {0}",ex),CrmServerManTrace.Sw.Info);
                throw;
            }
        }
        
        void RadGrid1_DeleteCommand(object source,GridCommandEventArgs e)
        {
			if (CrmServerManTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmServerManager RadGrid1_DeleteCommand BEG.",CrmServerManTrace.Sw.Info);
            GridEditableItem Item           =   e.Item as GridEditableItem;
            try
            {
                int CrmServerID             =   (int)(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex][ "CrmServerId"]);
                CrmManDB.DeleteCrmServer(CrmServerID);
		        if (CrmServerManTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmServerManager RadGrid1_DeleteCommand END CrmServerID: {0}.",CrmServerID),CrmServerManTrace.Sw.Info);
            }
            catch (Exception ex)
            {
				if (CrmServerManTrace.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmServerManager RadGrid1_InsertCommand ex: {0}",ex),CrmServerManTrace.Sw.Info);
                throw;
            }
        }
        
        // Go to install Org
        void RadGrid1_ItemCommand(object source,GridCommandEventArgs e)
        {
	        if (CrmServerManTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmServerManager RadGrid1_ItemCommand BEG CommandName: {0}.",e.CommandName),CrmServerManTrace.Sw.Info);
            if ( e.CommandName == "InstallCrmOrg" )
            {
                int CrmServerId     =   (RadGrid1.SelectedValue == null ) ? -1:(int)RadGrid1.SelectedValue;
                if (CrmServerManTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmServerManager RadGrid1_ItemCommand CrmServerId: {0}.",CrmServerId),CrmServerManTrace.Sw.Info);
                if ( CrmServerId != -1 )
                {
                    string Url      =   Config.ModulesPath+"/CrmServerManager/InstallCrmOrg.aspx";
                    Url             =   HttpUrlBuilder.BuildUrlWithCustomAttributes(Url, PageID,string.Format("mId={0}&CrmServerId={1}",ModuleID,CrmServerId));
                    ADNPage.Redirect(Url,true);
                }
            }
			if (CrmServerManTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmServerManager RadGrid1_ItemCommand END.",CrmServerManTrace.Sw.Info);
        }

        #endregion RadGrid for Crm Servers

        #region RadGrid for Crm Related Portals

        void RadGrid2_DataBound(object sender,EventArgs e)
        {
			if (CrmServerManTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmServerManager RadGrid2_DataBound BEG RadGrid2.Items.Count: {0}",RadGrid2.Items.Count),CrmServerManTrace.Sw.Info);
            if ( RadGrid2.Items.Count > 0 )
            {
                if( RadGrid2.SelectedValue == null )
                    RadGrid2.Items[0].Selected                          =   true;
            }
			if (CrmServerManTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmServerManager RadGrid3_DataBound END.",CrmServerManTrace.Sw.Info);
        }

        void RadGrid2_ItemDataBound(object sender, GridItemEventArgs e)
        {
			if (CrmServerManTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmServerManager RadGrid2_ItemDataBound BEG OwnerTableView.Name: {0}",e.Item.OwnerTableView.Name),CrmServerManTrace.Sw.Info);
            if ( !( e.Item is GridEditableItem ) )
                return;
            GridEditableItem Item                           =   e.Item as GridEditableItem;
		    if (CrmServerManTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmServerManager RadGrid2_ItemDataBound Item.IsInEditMode: {0}",Item.IsInEditMode),CrmServerManTrace.Sw.Info);
            if (Item.IsInEditMode)
            {
                DataRowView rw                              =   null;
                if ( !Item.OwnerTableView.IsItemInserted )
                    rw                                      =   (DataRowView)e.Item.DataItem;
                GridEditManager editMan                     =   Item.EditManager;

                GridDropDownListColumnEditor editor         =   (GridDropDownListColumnEditor)editMan.GetColumnEditor( "PortalAlias" );
                //in case you have RadComboBox editor for the GridDropDownColumn (this is the default editor),         
                //you will need to use ComboBoxControl below instead of DropDownListControl
                //Then you can modify the list control as per your custom conventions
                SqlDataReader rd                            =   null;
                try
                {
                    rd                                      =   new PortalsDB().GetPortals();
                    editor.DataSource                       =   rd;
                    editor.DataBind();
                    if (rw != null)
                    {
                        RadComboBoxItem it                  =   editor.ComboBoxControl.Items.FindItemByValue(rw["PortalID"].ToString());
                        if (it != null)
                            it.Selected                     =   true;
                    }
                }
                catch ( Exception ex )
                {
				    if (CrmServerManTrace.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmServerManager RadGrid2_ItemDataBound ex: {0}",ex),CrmServerManTrace.Sw.Info);
                    throw;
                }
                finally
                {
                    if ( rd != null )
                        rd.Close();
                }
            }
            else
            {
                DataRowView rw                              =   (DataRowView)e.Item.DataItem;
                string val                                  =   (string)rw["PortalAlias"];
                if (CrmServerManTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmServerManager RadGrid2_ItemDataBound val: {0}",val),CrmServerManTrace.Sw.Info);
                Item["PortalAlias"].Text                    =   val;
                Label Lbl                                   =   (Label)e.Item.FindControl("LblType");
                if ( Lbl != null )
                {
                    string sType                            =   Lbl.Text;
                    PortalType pType                        =   (PortalType)int.Parse(sType);
                    if (CrmServerManTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmServerManager RadGrid2_ItemDataBound pType: {0}", pType), CrmServerManTrace.Sw.Info);
                    Lbl.Text                                =   pType.ToString();
                }
            }
        }

        private void RadGrid2_InsertCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
        {
			if (CrmServerManTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmServerManager RadGrid2_InsertCommand BEG.",CrmServerManTrace.Sw.Info);
            GridEditableItem Item       =   e.Item as GridEditableItem;
            if ( RadGrid1.SelectedValue == null )
            {
			    if (CrmServerManTrace.Sw.TraceVerbose)
                    Trace2.WriteLine("[V]CrmServerManager RadGrid2_InsertCommand END No CrmServerId cancelling.",CrmServerManTrace.Sw.Info);
                e.Canceled              =   true;
                return;
            }

            int CrmServerID             =   (int)RadGrid1.SelectedValue;
			if (CrmServerManTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmServerManager RadGrid2_InsertCommand CrmServerID: {0}",CrmServerID),CrmServerManTrace.Sw.Info);
            Hashtable newValues         =   new Hashtable();
            e.Item.OwnerTableView.ExtractValuesFromItem(newValues, Item);

            try
            {
                int newPortalID         =   int.Parse(newValues["PortalAlias"].ToString()); // yes it is the int value from the RadComboBox
			    if (CrmServerManTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmServerManager RadGrid2_InsertCommand newPortalID: {0}",newPortalID),CrmServerManTrace.Sw.Info);
                DBCrmServer objSrv      =   CrmManDB.GetCrmServerObj(CrmServerID);
                CrmManDB.AddPortalCrmServer(CrmServerID,newPortalID,(objSrv.MainPortalID == -1));
			    if (CrmServerManTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmServerManager RadGrid2_InsertCommand END CrmServerID: {0}, newPortalID: {1}",CrmServerID,newPortalID),CrmServerManTrace.Sw.Info);
                RefreshCommands(CrmServerID);
            }
            catch (DuplicateKeyException dex)
            {
				if (CrmServerManTrace.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmServerManager RadGrid2_InsertCommand ex: {0}",dex),CrmServerManTrace.Sw.Info);
                string msg              =   LocalizeHelper.Localize("CRMSERVERMAN_PORTALALREADYCONNECTED","Portal already connected to another Crm Server");
                RadGrid2.Controls.Add(new LiteralControl(msg));
            }
            catch (Exception ex)
            {
				if (CrmServerManTrace.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmServerManager RadGrid2_InsertCommand ex: {0}",ex),CrmServerManTrace.Sw.Info);
                throw;
            }
        }
        
        
        void RadGrid2_DeleteCommand(object source,GridCommandEventArgs e)
        {
			if (CrmServerManTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmServerManager RadGrid2_DeleteCommand BEG.",CrmServerManTrace.Sw.Info);
            GridEditableItem Item       =   e.Item as GridEditableItem;

            int CrmServerID             =   (int)(Item.OwnerTableView.DataKeyValues[Item.ItemIndex][ "CrmServerId"]);
            int PortalID                =   (int)(Item.OwnerTableView.DataKeyValues[Item.ItemIndex][ "PortalId"]);
			if (CrmServerManTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmServerManager RadGrid2_DeleteCommand CrmServerID: {0}, PortalID: {1}",CrmServerID,PortalID),CrmServerManTrace.Sw.Info);
            try
            {
                CrmManDB.DeletePortalCrmServer(CrmServerID,PortalID);
                RefreshCommands(CrmServerID);
            }
            catch (Exception ex)
            {
				if (CrmServerManTrace.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmServerManager RadGrid2_DeleteCommand ex: {0}",ex),CrmServerManTrace.Sw.Info);
                throw;
            }
        }

        void RadGrid2_ItemCommand(object source,GridCommandEventArgs e)
        {
	        if (CrmServerManTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmServerManager RadGrid2_ItemCommand BEG CommandName: {0}.",e.CommandName),CrmServerManTrace.Sw.Info);
            if ( e.CommandName == "InstallCrmOrg" )
            {
                int CrmServerId     =   (RadGrid1.SelectedValue == null ) ? -1:(int)RadGrid1.SelectedValue;
                int PortalId        =   (RadGrid2.SelectedValue == null ) ? -1:(int)RadGrid2.SelectedValue;
                if (CrmServerManTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmServerManager RadGrid2_ItemCommand CrmServerId: {0}.",CrmServerId),CrmServerManTrace.Sw.Info);
                if (( CrmServerId != -1 ) && ( PortalId != -1) )
                {
                    string Url      =   Config.ModulesPath+"/CrmServerManager/InstallCrmOrg.aspx";
                    Url             =   HttpUrlBuilder.BuildUrlWithCustomAttributes(Url, PageID,string.Format("mId={0}&CrmServerId={1}&portalid={2}",ModuleID,CrmServerId,PortalId));
                    ADNPage.Redirect(Url,true);
                }
            }
			if (CrmServerManTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmServerManager RadGrid2_ItemCommand END.",CrmServerManTrace.Sw.Info);
        }
        
        #endregion RadGrid for Related Portals
        
        #region RadGrid for Crm Related Entities

        void RadGrid3_DataBound(object sender,EventArgs e)
        {
			if (CrmServerManTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmServerManager RadGrid3_DataBound BEG RadGrid3.Items.Count: {0}",RadGrid3.Items.Count),CrmServerManTrace.Sw.Info);
            if ( RadGrid3.Items.Count > 0 )
            {
                if( RadGrid3.SelectedValue == null )
                    RadGrid3.Items[0].Selected                          =   true;
            }
			if (CrmServerManTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmServerManager RadGrid3_DataBound END.",CrmServerManTrace.Sw.Info);
        }

        void RadGrid3_ItemDataBound(object sender, GridItemEventArgs e)
        {
			if (CrmServerManTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmServerManager RadGrid3_ItemDataBound BEG.",CrmServerManTrace.Sw.Info);
            if ( !( e.Item is GridEditableItem ) )
                return;
            GridEditableItem Item   =   e.Item as GridEditableItem;
		    if (CrmServerManTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmServerManager RadGrid3_ItemDataBound Item.IsInEditMode: {0}",Item.IsInEditMode),CrmServerManTrace.Sw.Info);
            if (Item.IsInEditMode)
            {
                DataRowView rw                              =   null;
                if ( !Item.OwnerTableView.IsItemInserted )
                    rw                                      =   (DataRowView)e.Item.DataItem;
                GridEditManager editMan                     =   Item.EditManager;

                GridDropDownListColumnEditor editor         =   (GridDropDownListColumnEditor)editMan.GetColumnEditor( "SchemaName" );
                // In edit mode we display a special column Schema/Version allowing to select the good version
                try
                {
                    DataTable Tb                            =   CrmManDB.GetAllCrmEntityTb();
                    Tb.Columns.Add("SchemaNameVersion",typeof(string));
                    foreach ( DataRow vrw in Tb.Rows )
                    {
                        vrw["SchemaNameVersion"]            =   string.Format("{0}/{1}",vrw["SchemaName"],vrw["EntityVersion"]);
                    }
                    editor.DataSource                       =   Tb;
                    editor.DataBind();
                    if (rw != null)
                    {
                        RadComboBoxItem it                  =   editor.ComboBoxControl.Items.FindItemByValue(rw["EntityId"].ToString());
                        if (it != null)
                            it.Selected                     =   true;
                    }
                }
                catch ( Exception ex )
                {
				    if (CrmServerManTrace.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmServerManager RadGrid3_ItemDataBound ex: {0}",ex),CrmServerManTrace.Sw.Info);
                    throw;
                }
            }
            else
            {
                DataRowView rw                              =   (DataRowView)e.Item.DataItem;
                string val                                  =   (string)rw["SchemaName"];
                if (CrmServerManTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmServerManager RadGrid3_ItemDataBound val: {0}",val),CrmServerManTrace.Sw.Info);
                Item["SchemaName"].Text                    =   val;
            }

        }

        private void RadGrid3_InsertCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
        {
			if (CrmServerManTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmServerManager RadGrid3_InsertCommand BEG OwnerTableView.Name: {0}",e.Item.OwnerTableView.Name),CrmServerManTrace.Sw.Info);
            GridEditableItem Item       =   e.Item as GridEditableItem;

            if ( RadGrid1.SelectedValue == null )
            {
			    if (CrmServerManTrace.Sw.TraceVerbose)
                    Trace2.WriteLine("[V]CrmServerManager RadGrid3_InsertCommand END No CrmServerId cancelling.",CrmServerManTrace.Sw.Info);
                e.Canceled              =   true;
                return;
            }

            int CrmServerID             =   (int)RadGrid1.SelectedValue;
			if (CrmServerManTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmServerManager RadGrid3_InsertCommand CrmServerID: {0}",CrmServerID),CrmServerManTrace.Sw.Info);
            Hashtable newValues         =   new Hashtable();
            e.Item.OwnerTableView.ExtractValuesFromItem(newValues, Item);

            try
            {
                int CrmEntityId            =   int.Parse(newValues["SchemaName"].ToString()); // yes it is the int value from the RadComboBox
                DBCrmEntity oEntity     =   CrmManDB.GetCrmEntityObj(CrmEntityId);
			    if (CrmServerManTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmServerManager RadGrid3_InsertCommand CrmEntityId: {0}",CrmEntityId),CrmServerManTrace.Sw.Info);
                CrmManDB.AddCrmServerEntity(CrmEntityId,CrmServerID,oEntity.EntityVersion);
                RefreshCommands(CrmServerID);
			    if (CrmServerManTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmServerManager RadGrid3_InsertCommand END CrmServerID: {0}, CrmEntityId: {1}",CrmServerID,CrmEntityId),CrmServerManTrace.Sw.Info);
            }
            catch (Exception ex)
            {
				if (CrmServerManTrace.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmServerManager RadGrid3_InsertCommand ex: {0}",ex),CrmServerManTrace.Sw.Info);
                throw;
            }
        }
        
        void RadGrid3_DeleteCommand(object source,GridCommandEventArgs e)
        {
			if (CrmServerManTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmServerManager RadGrid3_DeleteCommand BEG.",CrmServerManTrace.Sw.Info);
            GridEditableItem Item       =   e.Item as GridEditableItem;

            int CrmServerID             =   (int)(Item.OwnerTableView.DataKeyValues[Item.ItemIndex][ "CrmServerId"]);
            int CrmEntityId                =   (int)(Item.OwnerTableView.DataKeyValues[Item.ItemIndex][ "EntityId"]);
			if (CrmServerManTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmServerManager RadGrid3_DeleteCommand CrmServerID: {0}, CrmEntityId: {1}",CrmServerID,CrmEntityId),CrmServerManTrace.Sw.Info);
            try
            {
                CrmManDB.DeleteCrmServerEntity(CrmEntityId,CrmServerID);
                RefreshCommands(CrmServerID);
            }
            catch (Exception ex)
            {
				if (CrmServerManTrace.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmServerManager RadGrid3_DeleteCommand ex: {0}",ex),CrmServerManTrace.Sw.Info);
                throw;
            }
        }

        void RadGrid3_ItemCommand(object source,GridCommandEventArgs e)
        {
	        if (CrmServerManTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmServerManager RadGrid3_ItemCommand BEG CommandName: {0}.",e.CommandName),CrmServerManTrace.Sw.Info);
            if ( e.CommandName == "UpdateEntity" )
            {
                int CrmServerId     =   (RadGrid1.SelectedValue == null ) ? -1:(int)RadGrid1.SelectedValue;
                int CrmEntityId     =   (RadGrid3.SelectedValue == null ) ? -1:(int)RadGrid3.SelectedValue;
                if (CrmServerManTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmServerManager RadGrid3_ItemCommand CrmServerId: {0}.",CrmServerId),CrmServerManTrace.Sw.Info);
                if ( ( CrmServerId != -1 ) && ( CrmEntityId != -1 ) )
                {
                    string Url      =   Config.ModulesPath+"/CrmServerManager/UpdateCrmEntity.aspx";
                    Url             =   HttpUrlBuilder.BuildUrlWithCustomAttributes(Url, PageID,string.Format("mId={0}&crmserverid={1}&crmentityid={2}",ModuleID,CrmServerId,CrmEntityId));
                    ADNPage.Redirect(Url,true);
                }
            }
			if (CrmServerManTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmServerManager RadGrid3_ItemCommand END.",CrmServerManTrace.Sw.Info);
        }

        #endregion RadGrid for Related Entities

        #region Std Overrides

        public override void Page_PreInit(object sender, EventArgs e)
        {
			if (CrmServerManTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmServerManager Page_PreInit BEG.",(CrmServerManTrace.Sw.TraceVerbose) ? CrmServerManTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
            base.Page_PreInit(sender, e);
			if (CrmServerManTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmServerManager Page_PreInit END.",(CrmServerManTrace.Sw.TraceVerbose) ? CrmServerManTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
        }
        
        override protected void OnInit(EventArgs e)
		{
			InitializeComponent();
			base.OnInit(e);
		}

        private void InitializeComponent() 
        {
			Load                        +=  new EventHandler(Page_Load);
            
            RadGrid1.NeedDataSource     +=  new GridNeedDataSourceEventHandler(RadGrid1_NeedDataSource);
            RadGrid1.ItemDataBound      +=  new GridItemEventHandler(RadGrid1_ItemDataBound);
            RadGrid1.DeleteCommand      +=  new GridCommandEventHandler(RadGrid1_DeleteCommand);
            RadGrid1.InsertCommand      +=  new GridCommandEventHandler(RadGrid1_InsertCommand);
            RadGrid1.UpdateCommand      +=  new GridCommandEventHandler(RadGrid1_UpdateCommand);
            RadGrid1.SelectedIndexChanged += new EventHandler(RadGrid1_SelectedIndexChanged);
            RadGrid1.DataBound          +=  new EventHandler(RadGrid1_DataBound);

            RadGrid1.ItemCommand        +=  new GridCommandEventHandler(RadGrid1_ItemCommand);
            
            RadGrid2.NeedDataSource     +=  new GridNeedDataSourceEventHandler(RadGrid2_NeedDataSource);
            RadGrid2.ItemDataBound      +=  new GridItemEventHandler(RadGrid2_ItemDataBound);
            RadGrid2.InsertCommand      +=  new GridCommandEventHandler(RadGrid2_InsertCommand);
            RadGrid2.DeleteCommand      +=  new GridCommandEventHandler(RadGrid2_DeleteCommand);
            RadGrid2.DataBound          +=  new EventHandler(RadGrid2_DataBound);
            RadGrid2.ItemCommand        +=  new GridCommandEventHandler(RadGrid2_ItemCommand);
            
            RadGrid3.NeedDataSource     +=  new GridNeedDataSourceEventHandler(RadGrid3_NeedDataSource);
            RadGrid3.ItemDataBound      +=  new GridItemEventHandler(RadGrid3_ItemDataBound);
            RadGrid3.DeleteCommand      +=  new GridCommandEventHandler(RadGrid3_DeleteCommand);
            RadGrid3.InsertCommand      +=  new GridCommandEventHandler(RadGrid3_InsertCommand);
            RadGrid3.DataBound          +=  new EventHandler(RadGrid3_DataBound);
            RadGrid3.ItemCommand        +=  new GridCommandEventHandler(RadGrid3_ItemCommand);
		}

		#endregion
    }
}
